<?php
/**
* 商品信息表管理模型
*/
class GoodsDetailModel extends Model{
    public $table='goods_detail';
	
    /*添加商品属性
     **/
    public function addInfo($gid){
    	//接收提交图片的地址
    	$showImg=isset($_POST['showImg'])?$_POST['showImg']:array();
		$img=new image();
		//三个字符串分别存放小、中、大三张图的路径
		$simg='';
		$mimg='';
		$bimg='';
		//依次把每张图片缩成小图、中图
		foreach ($showImg as $key => $v) {
			//获得每张图片的后缀名，分别在后缀名前加small、mid区别小中图，大图用原来的名称
			$type=strrchr($v,'.');
			$newPath=str_replace('showImgTemp', 'showImg', $v);
			$small=str_replace($type, 'small'.$type, $newPath);
			$mid=str_replace($type, 'mid'.$type, $newPath);
			$img->thumb($v,$small,75,100,1);
			$img->thumb($v,$mid,420,560,1);
			//把所有相同大小的图的路径拼接到一起
			$simg.=$small."|";
			$mimg.=$mid."|";
			$bimg.=$newPath."|";
			if(is_file($v)){
				copy($v, $newPath);
				unlink($v);
			}
		}
		//整理要写入数据库的数据
    	$data=array(
			'goods_gid'=>$gid,
			'simg'=>$simg,
			'mimg'=>$mimg,
			'bimg'=>$bimg,
			'info'=>Q('post.info','')
		);
		$this->add($data);		
    }
	
	
	/*编辑商品详情
	 **/
	public function editInfo(){
	    $gid=Q('post.gid',0,'intval');
		//获得编辑之前的信息
		$oldImg=$this->where("goods_gid={$gid}")->getField('bimg');
		$oldImg=explode('|',trim($oldImg,'|'));
		$newImg=isset($_POST['showImg'])?$_POST['showImg']:array();
		//判断图片是否有改变
		//如果图片未更换，直接更新数据
		if(array_diff($oldImg, $newImg)==array() && array_diff($newImg, $oldImg)==array()){
			$this->where("goods_gid={$gid}")->update();
		//否侧处理图片，再更新数据
		}else{
			//三个字符串分别存放小、中、大三张图的路径
			$simg='';$mimg='';$bimg='';
			$img=new image();
			foreach ($newImg as $i) {
				$type=strrchr($i,'.');
				$newPath=str_replace('showImgTemp','showImg',$i);
				$small=str_replace($type, 'small'.$type, $newPath);
				$mid=str_replace($type, 'mid'.$type, $newPath);
				$simg.=$small."|";
				$mimg.=$mid."|";
				$bimg.=$newPath."|";
				//如果是更新的图片，进行缩略处理后，删除临时图
				if(!in_array($i,$oldImg) &&is_file($i)){
					$img->thumb($i,$small,75,100,1);
					$img->thumb($i,$mid,420,560,1);
					copy($i,$newPath);
					unlink($i);
				}
			}
			$data=array(
			'goods_gid'=>$gid,
			'simg'=>$simg,
			'mimg'=>$mimg,
			'bimg'=>$bimg,
			'info'=>Q('post.info','')
			);
			$this->where("goods_gid={$gid}")->update($data);
			//获得被移出的图片，删除它
			$oldDiff=array_diff($oldImg, $newImg);
			if(!empty($oldDiff)){
				foreach ($oldDiff as $k => $i) {
					$type=strrchr($i,'.');
					$small=str_replace($type, 'small'.$type, $i);
					$mid=str_replace($type, 'mid'.$type, $i);
					is_file($i)&&unlink($i);
					is_file($small)&&unlink($small);
					is_file($mid)&&unlink($mid);
				}
			}
		}
	}
	
}
    
	
	
	
	
	
	
	
	
	
	
	
	
	
    
?>